<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录 - 闲鱼自动回复管理系统</title>
  <link rel="stylesheet" href="/static/lib/bootstrap/bootstrap.min.css">
  <link rel="stylesheet" href="/static/lib/bootstrap-icons/bootstrap-icons.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      --primary-color: #5c6ac4;
      --primary-dark: #4c59b8;
      --secondary-color: #6c757d;
      --success-color: #06c167;
      --danger-color: #f04438;
      --warning-color: #f79009;
      --text-primary: #1a1a1a;
      --text-secondary: #6c757d;
      --bg-light: #f8fafc;
      --border-color: #e5e7eb;
      --white: #ffffff;
    }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow-x: hidden;
      background-attachment: fixed;
      padding-bottom: 50px;
    }

    .login-wrapper {
      display: flex;
      width: 100%;
      max-width: 1100px;
      min-height: 600px;
      background: var(--white);
      border-radius: 16px;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
      overflow: hidden;
      margin: 20px;
    }

    .login-left {
      flex: 1;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
      padding: 60px 40px;
      position: relative;
      overflow: hidden;
    }

    .login-left::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: url('data:image/svg+xml,<svg width="60" height="60" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="rgba(255,255,255,0.1)" fill-opacity="0.1"><circle cx="30" cy="30" r="2"/></g></g></svg>') repeat;
      opacity: 0.5;
    }

    .brand-logo-image {
      position: fixed;
      top: 20px;
      left: 20px;
      z-index: 15;
      display: flex;
      align-items: center;
      background: transparent;
      border-radius: 12px;
      padding: 12px 16px;
      gap: 10px;
    }

    .logo-image {
      width: 40px;
      height: 40px;
      object-fit: contain;
      border-radius: 6px;
    }

    .logo-text {
      font-size: 1.4rem;
      font-weight: 700;
      margin: 0;
      height: 45px;
      line-height: 45px;
      color: white;
      text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
      font-family: 'SimSun', '宋体', serif;
      letter-spacing: 1px;
      position: relative;
      display: flex;
      align-items: center;
      text-decoration: none;
    }

    .logo-text::after {
      display: none;
    }

    .brand-logo {
      position: relative;
      z-index: 2;
      text-align: center;
      margin-bottom: 40px;
    }

    .brand-logo i {
      font-size: 4rem;
      margin-bottom: 20px;
      display: block;
      opacity: 0.9;
    }

    .brand-title {
      font-size: 2.5rem;
      font-weight: 700;
      margin-bottom: 10px;
      line-height: 1.2;
    }

    .brand-subtitle {
      font-size: 1.1rem;
      opacity: 0.9;
      line-height: 1.5;
    }

    .feature-list {
      position: relative;
      z-index: 2;
      margin-top: 40px;
      text-align: left;
    }

    .feature-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      opacity: 0.9;
    }

    .feature-item i {
      font-size: 1.2rem;
      margin-right: 12px;
      width: 20px;
    }

    .login-right {
      flex: 1;
      padding: 60px 50px;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .login-header {
      text-align: center;
      margin-bottom: 40px;
    }

    .login-title {
      font-size: 2rem;
      font-weight: 700;
      color: var(--text-primary);
      margin-bottom: 8px;
    }

    .login-description {
      font-size: 1rem;
      color: var(--text-secondary);
    }

    .login-tabs {
      margin-bottom: 30px;
    }

    .btn-group .btn {
      border-radius: 8px;
      font-weight: 500;
      padding: 10px 16px;
      border: 2px solid var(--border-color);
      background: var(--white);
      color: var(--text-secondary);
      transition: all 0.2s ease;
    }

    .btn-group .btn:hover {
      border-color: var(--primary-color);
      color: var(--primary-color);
    }

    .btn-group .btn.active,
    .btn-group input:checked + .btn {
      background: var(--primary-color);
      border-color: var(--primary-color);
      color: white;
    }

    .form-group {
      margin-bottom: 24px;
    }

    .form-label {
      font-weight: 600;
      color: var(--text-primary);
      margin-bottom: 8px;
      display: block;
    }

    .input-group {
      position: relative;
    }

    .form-control {
      border: 2px solid var(--border-color);
      border-radius: 8px;
      padding: 14px 16px;
      font-size: 1rem;
      transition: all 0.2s ease;
      background: var(--white);
      width: 100%;
    }

    .form-control:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 4px rgba(92, 106, 196, 0.1);
      outline: none;
    }

    .form-control::placeholder {
      color: var(--text-secondary);
    }

    .input-with-icon {
      position: relative;
    }

    .input-with-icon i {
      position: absolute;
      left: 16px;
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-secondary);
      z-index: 2;
    }

    .input-with-icon .form-control {
      padding-left: 48px;
    }

    .btn-login {
      background: var(--primary-color);
      border: none;
      border-radius: 8px;
      padding: 14px;
      font-size: 1rem;
      font-weight: 600;
      width: 100%;
      color: white;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
    }

    .btn-login:hover {
      background: var(--primary-dark);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(92, 106, 196, 0.3);
    }

    .btn-login:active {
      transform: translateY(0);
    }

    .btn-login:disabled {
      background: var(--text-secondary);
      transform: none;
      box-shadow: none;
    }

    .alert {
      border-radius: 8px;
      border: none;
      padding: 12px 16px;
      margin-bottom: 24px;
    }

    .alert-danger {
      background: rgba(240, 68, 56, 0.1);
      color: var(--danger-color);
      border-left: 4px solid var(--danger-color);
    }

    .captcha-row {
      display: flex;
      gap: 12px;
      align-items: end;
    }

    .captcha-input {
      flex: 2;
    }

    .captcha-image-wrapper {
      flex: 1;
      position: relative;
    }

    .captcha-image {
      width: 100%;
      height: 48px;
      border: 2px solid var(--border-color);
      border-radius: 8px;
      cursor: pointer;
      transition: border-color 0.2s ease;
    }

    .captcha-image:hover {
      border-color: var(--primary-color);
    }

    .code-input-group {
      display: flex;
      gap: 8px;
    }

    .code-input-group .form-control {
      flex: 1;
    }

    .btn-send-code {
      background: var(--white);
      border: 2px solid var(--primary-color);
      color: var(--primary-color);
      padding: 14px 20px;
      border-radius: 8px;
      font-weight: 500;
      white-space: nowrap;
      transition: all 0.2s ease;
    }

    .btn-send-code:hover:not(:disabled) {
      background: var(--primary-color);
      color: white;
    }

    .btn-send-code:disabled {
      border-color: var(--border-color);
      color: var(--text-secondary);
      background: var(--bg-light);
    }

    .form-text {
      font-size: 0.875rem;
      color: var(--text-secondary);
      margin-top: 6px;
    }

    .form-text.text-success {
      color: var(--success-color) !important;
    }

    .form-text.text-danger {
      color: var(--danger-color) !important;
    }

    .divider {
      display: flex;
      align-items: center;
      margin: 24px 0;
      color: var(--text-secondary);
      font-size: 0.875rem;
    }

    .divider::before,
    .divider::after {
      content: '';
      flex: 1;
      height: 1px;
      background: var(--border-color);
    }

    .divider span {
      padding: 0 16px;
    }

    .register-link {
      text-align: center;
      margin-top: 24px;
      padding-top: 24px;
      border-top: 1px solid var(--border-color);
    }

    .register-link a {
      color: var(--primary-color);
      text-decoration: none;
      font-weight: 500;
      display: inline-flex;
      align-items: center;
      gap: 4px;
      transition: color 0.2s ease;
    }

    .register-link a:hover {
      color: var(--primary-dark);
      text-decoration: underline;
    }



    .loading-spinner {
      width: 16px;
      height: 16px;
      border: 2px solid transparent;
      border-top: 2px solid currentColor;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .login-form-section {
      transition: all 0.3s ease;
    }

    .footer {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      text-align: center;
      padding: 15px;
      z-index: 10;
    }

    .footer-text {
      color: white;
      font-size: 0.875rem;
      margin: 0;
      text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .login-wrapper {
        flex-direction: column;
        margin: 10px;
        border-radius: 12px;
      }

      .login-left {
        padding: 40px 30px;
        text-align: center;
      }

      .brand-title {
        font-size: 2rem;
      }

      .feature-list {
        display: none;
      }

      .login-right {
        padding: 40px 30px;
      }

      .login-title {
        font-size: 1.75rem;
      }
    }

    @media (max-width: 480px) {
      .login-wrapper {
        margin: 5px;
      }

      .login-left,
      .login-right {
        padding: 30px 20px;
      }

      .captcha-row {
        flex-direction: column;
        gap: 16px;
      }

      .captcha-input,
      .captcha-image-wrapper {
        flex: none;
      }

      .code-input-group {
        flex-direction: column;
      }

      .footer {
        padding: 12px;
      }

      .footer-text {
        font-size: 0.8rem;
      }

      .brand-logo-image {
        top: 15px;
        left: 15px;
        padding: 8px 12px;
      }

      .logo-image {
        width: 32px;
        height: 32px;
      }

      .logo-text {
        font-size: 1rem;
        height: 32px;
        line-height: 32px;
        letter-spacing: 0.5px;
      }
    }
  </style>
</head>
<body>
  <!-- 整体背景logo -->
  <a href="https://admin.jhsrvip.cn/login" class="brand-logo-image" target="_blank" style="text-decoration: none;">
    <img src="/static/聚合云图标.png" alt="聚合云" class="logo-image">
    <span class="logo-text">聚合云</span>
  </a>

  <div class="login-wrapper">
    <!-- 左侧品牌区域 -->
    <div class="login-left">
      <div class="brand-logo">
        <i class="bi bi-chat-dots-fill"></i>
        <div class="brand-title">聚合云·闲鱼管理系统</div>
        <div class="brand-subtitle">智能化客服管理平台</div>
      </div>
      
      <div class="feature-list">
        <div class="feature-item">
          <i class="bi bi-robot"></i>
          <span>AI智能回复</span>
        </div>
        <div class="feature-item">
          <i class="bi bi-lightning-fill"></i>
          <span>自动发货系统</span>
        </div>
        <div class="feature-item">
          <i class="bi bi-shield-check"></i>
          <span>安全稳定</span>
        </div>
        <div class="feature-item">
          <i class="bi bi-graph-up"></i>
          <span>数据分析</span>
        </div>
      </div>
    </div>

    <!-- 右侧登录区域 -->
    <div class="login-right">
      <div class="login-header">
        <h1 class="login-title">欢迎回来</h1>
        <p class="login-description">请登录您的账户以继续使用</p>
      </div>

      <!-- 登录方式选择 -->
      <div class="login-tabs">
        <div class="btn-group w-100" role="group">
          <input type="radio" class="btn-check" name="loginType" id="usernameLogin" value="username" checked>
          <label class="btn" for="usernameLogin">用户名登录</label>

          <input type="radio" class="btn-check" name="loginType" id="emailPasswordLogin" value="email-password">
          <label class="btn" for="emailPasswordLogin">邮箱密码</label>

          <input type="radio" class="btn-check" name="loginType" id="emailCodeLogin" value="email-code">
          <label class="btn" for="emailCodeLogin">邮箱验证码</label>
        </div>
      </div>

      <form id="loginForm">
        <!-- 用户名/密码登录 -->
        <div id="usernameLoginForm" class="login-form-section">
          <div class="form-group">
            <div class="input-with-icon">
              <i class="bi bi-person-fill"></i>
              <input type="text" class="form-control" id="username" placeholder="请输入用户名">
            </div>
          </div>

          <div class="form-group">
            <div class="input-with-icon">
              <i class="bi bi-lock-fill"></i>
              <input type="password" class="form-control" id="password" placeholder="请输入密码">
            </div>
          </div>
        </div>

        <!-- 邮箱/密码登录 -->
        <div id="emailPasswordLoginForm" class="login-form-section" style="display: none;">
          <div class="form-group">
            <div class="input-with-icon">
              <i class="bi bi-envelope-fill"></i>
              <input type="email" class="form-control" id="emailForPassword" placeholder="请输入邮箱地址">
            </div>
          </div>

          <div class="form-group">
            <div class="input-with-icon">
              <i class="bi bi-lock-fill"></i>
              <input type="password" class="form-control" id="emailPassword" placeholder="请输入密码">
            </div>
          </div>
        </div>

        <!-- 邮箱/验证码登录 -->
        <div id="emailCodeLoginForm" class="login-form-section" style="display: none;">
          <div class="form-group">
            <div class="input-with-icon">
              <i class="bi bi-envelope-fill"></i>
              <input type="email" class="form-control" id="emailForCode" placeholder="请输入邮箱地址">
            </div>
          </div>

          <!-- 图形验证码 -->
          <div class="form-group">
            <label class="form-label">图形验证码</label>
            <div class="captcha-row">
              <div class="captcha-input">
                <input type="text" class="form-control" id="captchaCode" placeholder="输入验证码" maxlength="4">
              </div>
              <div class="captcha-image-wrapper">
                <img id="captchaImage" src="" alt="点击刷新" class="captcha-image" onclick="refreshCaptcha()">
                <div id="captchaLoading" class="text-center position-absolute top-50 start-50 translate-middle" style="display: none;">
                  <div class="loading-spinner"></div>
                </div>
              </div>
            </div>
            <div class="form-text" id="captchaStatus">请输入图形验证码</div>
          </div>

          <!-- 邮箱验证码 -->
          <div class="form-group">
            <label class="form-label">邮箱验证码</label>
            <div class="code-input-group">
              <input type="text" class="form-control" id="verificationCode" placeholder="输入6位验证码" maxlength="6">
              <button type="button" class="btn-send-code" id="sendCodeBtn" onclick="sendVerificationCode()" disabled>
                发送验证码
              </button>
            </div>
            <div class="form-text" id="codeStatus">请先验证图形验证码</div>
          </div>
        </div>

        <div id="errorAlert" class="alert alert-danger d-none" role="alert">
          <i class="bi bi-exclamation-triangle-fill me-2"></i>
          <span id="errorMessage"></span>
        </div>

        <button type="submit" class="btn-login">
          <span class="loading-spinner" id="loadingSpinner" style="display: none;"></span>
          <span id="loginText">登录</span>
        </button>
      </form>

      <!-- 注册链接 -->
      <div id="registerSection" class="register-link">
        <span class="text-muted">还没有账号？</span>
        <a href="/register.html">
          <i class="bi bi-person-plus"></i>
          <span>立即注册</span>
        </a>
      </div>


    </div>
  </div>

  <!-- 底部版权信息 -->
  <div class="footer">
    <div class="footer-text">Power by Wins Tech 2025</div>
  </div>

  <script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
  <script>
    const loginForm = document.getElementById('loginForm');
    const errorAlert = document.getElementById('errorAlert');
    const errorMessage = document.getElementById('errorMessage');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const loginText = document.getElementById('loginText');
    
    function showError(message) {
      errorMessage.textContent = message;
      errorAlert.classList.remove('d-none');
    }
    
    function hideError() {
      errorAlert.classList.add('d-none');
    }
    
    function setLoading(isLoading) {
      const submitButton = loginForm.querySelector('.btn-login');
      if (isLoading) {
        loadingSpinner.style.display = 'block';
        loginText.textContent = '登录中...';
        submitButton.disabled = true;
      } else {
        loadingSpinner.style.display = 'none';
        loginText.textContent = '登录';
        submitButton.disabled = false;
      }
    }


    
    loginForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      hideError();
      setLoading(true);

      const loginType = document.querySelector('input[name="loginType"]:checked').value;
      let loginData = {};

      try {
        if (loginType === 'username') {
          const username = document.getElementById('username').value;
          const password = document.getElementById('password').value;

          if (!username || !password) {
            showError('请输入用户名和密码');
            return;
          }

          loginData = { username, password };
        } else if (loginType === 'email-password') {
          const email = document.getElementById('emailForPassword').value;
          const password = document.getElementById('emailPassword').value;

          if (!email || !password) {
            showError('请输入邮箱和密码');
            return;
          }

          if (!validateEmail(email)) {
            showError('请输入有效的邮箱地址');
            return;
          }

          loginData = { email, password };
        } else if (loginType === 'email-code') {
          const email = document.getElementById('emailForCode').value;
          const verificationCode = document.getElementById('verificationCode').value;

          if (!captchaVerified) {
            showError('请先验证图形验证码');
            return;
          }

          if (!email) {
            showError('请输入邮箱地址');
            return;
          }

          if (!validateEmail(email)) {
            showError('请输入有效的邮箱地址');
            return;
          }

          if (!verificationCode || verificationCode.length !== 6) {
            showError('请输入6位验证码');
            return;
          }

          loginData = { email, verification_code: verificationCode };
        }

        const response = await fetch('/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(loginData)
        });

        const result = await response.json();

        if (result.success) {
          // 保存token到localStorage
          localStorage.setItem('auth_token', result.token);

          // 保存用户信息到localStorage
          const userInfo = {
            user_id: result.user_id,
            username: result.username,
            is_admin: result.is_admin
          };
          localStorage.setItem('user_info', JSON.stringify(userInfo));

          // 检查是否有重定向URL
          const redirectUrl = localStorage.getItem('redirectAfterLogin');
          if (redirectUrl) {
            // 清除重定向URL
            localStorage.removeItem('redirectAfterLogin');
            // 跳转到原来的页面
            window.location.href = redirectUrl;
          } else {
            // 默认跳转到管理页面
            window.location.href = '/admin';
          }
        } else {
          showError(result.message);
        }
      } catch (error) {
        showError('登录失败，请检查网络连接');
      } finally {
        setLoading(false);
      }
    });
    
    // 检查是否已经登录
    const token = localStorage.getItem('auth_token');
    if (token) {
      // 验证token是否有效
      fetch('/verify', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      .then(response => response.json())
      .then(result => {
        if (result.authenticated) {
          window.location.href = '/admin';
        }
      })
      .catch(() => {
        // token无效，清除
        localStorage.removeItem('auth_token');
      });
    }

    // 登录方式切换相关变量
    let captchaVerified = false;
    let countdownTimer = null;
    let countdownSeconds = 0;
    let sessionId = generateSessionId();

    // 生成会话ID
    function generateSessionId() {
      return 'session_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
    }

    // 登录方式切换
    function switchLoginType() {
      const loginType = document.querySelector('input[name="loginType"]:checked').value;

      // 隐藏所有表单
      document.querySelectorAll('.login-form-section').forEach(section => {
        section.style.display = 'none';
      });

      // 显示对应表单
      if (loginType === 'username') {
        document.getElementById('usernameLoginForm').style.display = 'block';
      } else if (loginType === 'email-password') {
        document.getElementById('emailPasswordLoginForm').style.display = 'block';
      } else if (loginType === 'email-code') {
        document.getElementById('emailCodeLoginForm').style.display = 'block';
        // 每次切换到邮箱验证码登录时都加载验证码
        loadCaptcha();
      }

      hideError();
    }

    // 加载图形验证码
    async function loadCaptcha() {
      const captchaImage = document.getElementById('captchaImage');
      const captchaLoading = document.getElementById('captchaLoading');
      const captchaStatus = document.getElementById('captchaStatus');

      captchaLoading.style.display = 'block';
      captchaImage.style.opacity = '0.5';

      try {
        const response = await fetch('/generate-captcha', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ session_id: sessionId })
        });

        const result = await response.json();

        if (result.success) {
          captchaImage.src = result.captcha_image;
          captchaStatus.textContent = '请输入图形验证码，点击图片可刷新';
          captchaStatus.className = 'form-text';
          captchaVerified = false;
          updateSendCodeButton();
        } else {
          captchaStatus.textContent = '图形验证码加载失败，请刷新页面重试';
          captchaStatus.className = 'form-text text-danger';
        }
      } catch (error) {
        console.error('加载图形验证码失败:', error);
        captchaStatus.textContent = '图形验证码加载失败，请检查网络连接';
        captchaStatus.className = 'form-text text-danger';
      } finally {
        captchaLoading.style.display = 'none';
        captchaImage.style.opacity = '1';
      }
    }

    // 刷新图形验证码
    function refreshCaptcha() {
      loadCaptcha();
    }

    // 验证图形验证码
    async function verifyCaptcha() {
      const captchaCode = document.getElementById('captchaCode').value.trim();
      const captchaStatus = document.getElementById('captchaStatus');

      if (!captchaCode) {
        captchaStatus.textContent = '请输入图形验证码';
        captchaStatus.className = 'form-text';
        captchaVerified = false;
        updateSendCodeButton();
        return;
      }

      try {
        const response = await fetch('/verify-captcha', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            session_id: sessionId,
            captcha_code: captchaCode
          })
        });

        const result = await response.json();

        if (result.success) {
          captchaStatus.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i>图形验证码验证成功';
          captchaStatus.className = 'form-text text-success';
          captchaVerified = true;
        } else {
          captchaStatus.innerHTML = '<i class="bi bi-x-circle-fill me-1"></i>图形验证码错误，请重新输入';
          captchaStatus.className = 'form-text text-danger';
          captchaVerified = false;
          refreshCaptcha(); // 自动刷新验证码
        }

        updateSendCodeButton();

      } catch (error) {
        console.error('验证图形验证码失败:', error);
        captchaStatus.innerHTML = '<i class="bi bi-exclamation-triangle-fill me-1"></i>验证失败，请检查网络连接';
        captchaStatus.className = 'form-text text-danger';
        captchaVerified = false;
        updateSendCodeButton();
      }
    }

    // 更新发送验证码按钮状态
    function updateSendCodeButton() {
      const sendCodeBtn = document.getElementById('sendCodeBtn');
      const email = document.getElementById('emailForCode').value.trim();
      const codeStatus = document.getElementById('codeStatus');

      if (captchaVerified && email && validateEmail(email)) {
        sendCodeBtn.disabled = false;
        codeStatus.textContent = '图形验证码已验证，可以发送邮箱验证码';
        codeStatus.className = 'form-text text-success';
      } else {
        sendCodeBtn.disabled = true;
        if (!captchaVerified) {
          codeStatus.textContent = '请先验证图形验证码';
          codeStatus.className = 'form-text';
        } else if (!email) {
          codeStatus.textContent = '请先输入邮箱地址';
          codeStatus.className = 'form-text';
        } else if (!validateEmail(email)) {
          codeStatus.textContent = '请输入有效的邮箱地址';
          codeStatus.className = 'form-text text-danger';
        }
      }
    }

    // 邮箱格式验证
    function validateEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(email);
    }

    // 开始倒计时
    function startCountdown() {
      countdownSeconds = 60;
      const sendCodeBtn = document.getElementById('sendCodeBtn');
      const codeStatus = document.getElementById('codeStatus');

      sendCodeBtn.disabled = true;

      countdownTimer = setInterval(() => {
        countdownSeconds--;
        sendCodeBtn.textContent = `重新发送 (${countdownSeconds}s)`;
        codeStatus.innerHTML = `<i class="bi bi-clock-fill me-1"></i>验证码已发送，${countdownSeconds}秒后可重新发送`;
        codeStatus.className = 'form-text text-success';

        if (countdownSeconds <= 0) {
          clearInterval(countdownTimer);
          sendCodeBtn.disabled = false;
          sendCodeBtn.textContent = '发送验证码';
          codeStatus.textContent = '可以重新发送验证码';
          codeStatus.className = 'form-text';
        }
      }, 1000);
    }

    // 发送邮箱验证码
    async function sendVerificationCode() {
      const email = document.getElementById('emailForCode').value.trim();

      if (!captchaVerified) {
        showError('请先验证图形验证码');
        return;
      }

      if (!email) {
        showError('请先输入邮箱地址');
        return;
      }

      if (!validateEmail(email)) {
        showError('请输入有效的邮箱地址');
        return;
      }

      try {
        const response = await fetch('/send-verification-code', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            email: email,
            type: 'login',
            session_id: sessionId
          })
        });

        const result = await response.json();

        if (result.success) {
          startCountdown();
        } else {
          showError(result.message);
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        showError('发送验证码失败，请检查网络连接');
      }
    }

    // 检查注册状态
    async function checkRegistrationStatus() {
      try {
        const response = await fetch('/registration-status');
        if (response.ok) {
          const data = await response.json();
          const registerSection = document.getElementById('registerSection');
          if (registerSection) {
            registerSection.style.display = data.enabled ? 'block' : 'none';
          }
        }
      } catch (error) {
        console.error('检查注册状态失败:', error);
        // 出错时默认显示注册链接
      }
    }

    // 事件监听器
    document.addEventListener('DOMContentLoaded', function() {
      // 检查注册状态
      checkRegistrationStatus();

      // 登录方式切换
      document.querySelectorAll('input[name="loginType"]').forEach(radio => {
        radio.addEventListener('change', switchLoginType);
      });

      // 图形验证码输入框事件
      const captchaCodeInput = document.getElementById('captchaCode');
      if (captchaCodeInput) {
        captchaCodeInput.addEventListener('input', function() {
          if (this.value.length === 4) {
            verifyCaptcha();
          } else {
            captchaVerified = false;
            updateSendCodeButton();
            document.getElementById('captchaStatus').textContent = '请输入4位图形验证码';
            document.getElementById('captchaStatus').className = 'form-text';
          }
        });
      }

      // 邮箱输入框事件
      const emailForCodeInput = document.getElementById('emailForCode');
      if (emailForCodeInput) {
        emailForCodeInput.addEventListener('input', updateSendCodeButton);
      }
    });
  </script>
</body>
</html>
